package com.cait.dutyfree.action.admin;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import com.cait.dutyfree.dataaccess.UserServiceDAO;
import com.cait.dutyfree.pojo.LoginUser;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements ServletContextAware,
		SessionAware, ServletRequestAware {
	// =============================================================================
	private ServletContext servletContext;
	private HttpServletRequest request;
	private Map<String, Object> session;

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
	}

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.session = arg0;
	}

	@Override
	public void setServletContext(ServletContext arg0) {
		this.servletContext = arg0;
	}

	// ==============================================================================

	private UserServiceDAO userServiceDAO;

	public UserServiceDAO getUserServiceDAO() {
		return userServiceDAO;
	}

	public void setUserServiceDAO(UserServiceDAO userServiceDAO) {
		this.userServiceDAO = userServiceDAO;
	}

	// ===============================================================================

	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	// =================================================================================
	public String adminLogin() {
		System.out.println("*******************************************");
		return SUCCESS;
	}

	public String submitLogin() throws Exception {
		String result = this.getUserServiceDAO().userAuthentication(
				this.getUsername(), this.getPassword());
		if (result == "sucess") {
			// check for admin role
			LoginUser user = this.getUserServiceDAO().getUser(
					this.getUsername());
			if (user.getUserType().equals("admin")) {
				this.session.put("adminUser", user);
				return SUCCESS;
			} else {
				this.addActionError("You are not allowed to access here");
				return NONE;
			}
		} else {
			this.addActionError("Incorrect username/password");
			return NONE;
		}
	}

}
